<template>
  <div>
    <swiper class="swiper" indicator-dots="true" autoplay="true" interval="5000" duration="1000" style="height:350px;">
      <block v-for="(item, index) in goods.thumb" :index="index" :key="index">
        <swiper-item>
          <image :src="item.imgUrl" class="slide-image" mode="aspectFit" />
        </swiper-item>
      </block>
    </swiper>
    <van-row>
      <van-col span="24">
        <div class="goods-title">{{ goods.name }}</div>
      </van-col>
      <van-col span="24">
        <div class="goods-desc">{{ goods.descript }}</div>
      </van-col>
      <van-col span="24">
        <div class="goods-price">￥ {{ goods.price }}</div>
      </van-col>
    </van-row>
    <van-row>
      <van-col span="10">
        <div class="goods-express">运费：免运费</div>
      </van-col>
      <van-col span="14">
        <div class="goods-express">剩余：{{ goods.stock }}</div>
      </van-col>
    </van-row>
    <van-row>
      <van-col span="24" class="goods-detail">
        <wxParse :content="goods.detail"></wxParse>
      </van-col>
    </van-row>

    <van-goods-action>
      <van-goods-action-icon icon="home-o" text="主页" @click="toHome" />
      <van-goods-action-icon icon="like-o" text="喜欢" @click="like" v-if="!ifLike" />
      <van-goods-action-icon icon="like" text="喜欢" @click="like" v-if="ifLike" />
      <van-goods-action-icon icon="cart-o" text="购物车" @click="goToCart" />
      <van-goods-action-button text="立即购买" @click="openAddDialog" />
    </van-goods-action>
    <van-popup :show="showDialog" position="bottom" custom-style="height: 50%;min-height:25rem;" closeable round @close="closeDialog">
      <div class="sel-goods" style="padding:1.1rem;">
        <van-row>
          <van-col :span="8">
            <van-image width="80" height="80" :src="goods.imgUrl" />
          </van-col>
          <van-col :span="16">
            <div>价格：{{ goods.price }}</div>
            <div>剩余：{{ goods.stock }}</div>
            <div>{{ attrText }}</div>
          </van-col>
        </van-row>
        <block v-for="(treeNode, index) in sku.tree" :index="index" :key="index">
          <div style="margin:.2rem 0 .5rem 0;">{{ treeNode.k }}</div>
          <van-tag v-for="(treeV, index2) in treeNode.v" :index="index2" :key="index2" color="#f2826a" size="large" :plain="treeV.plain" style="margin-right:2px;" @click="chooseAttr(treeV, treeNode)">{{ treeV.name }}</van-tag>
        </block>
        <div class="buy-count">
          <div style="margin-bottom:.5rem;">购买数量</div>
          <van-stepper integer :value="selectedNum" v-model="selectedNum" :min="1" :max="goods.stock" @change="changeGoodsNum" />
        </div>
      </div>
      <van-goods-action>
        <van-goods-action-button class="buy-action" text="加入购物车" type="warning" @click="addCart" />
        <van-goods-action-button class="buy-action" text="立即购买" @click="buy" />
      </van-goods-action>
    </van-popup>
  </div>
</template>

<script>
import utils from "@/utils/index.js";
import wxParse from "mpvue-wxparse";
import store from "@/utils/store.js";

export default {
  components: {
    wxParse
  },
  data() {
    return {
      temp: 1,
      selectedNum: 1,
      skuSel: {},
      goods: { thumb: [] },
      sku: [],
      selSku: {},
      likeColor: 'black',
      ifLike: false,
      likeIcon: 'like-o',
      imgheights: [],
      showDialog: false,
      chooseAttrText: {},
      plainTest: false,
      skuData: {
        idGoods: "",
        stockNum: "",
        selectedNum: 1,
        price: "",
        idSku: "",
        selAttrKey: {},
        selAttrKeyList: [],
        selectedSkuComb: {
          attrKeyList: []
        }
      }
    };
  },

  computed: {
    attrText() {
      if (!this.sku.none_sku) {
        let ret = "选择：";
        for (let key in this.chooseAttrText) {
          ret += this.chooseAttrText[key] + ";";
        }
        return ret;
      }
      return "";
    }
  },
  methods: {

    getGoods(id) {
      this.$API.get("/goods/" + id).then(res => {

        let goods = res.data.goods;
        this.sku = res.data.sku;
        let chooseAttrText = {};
        for (let i = 0; i < this.sku.tree.length; i++) {
          chooseAttrText[this.sku.tree[i]["k_s"]] = this.sku.tree[i].k;
        }
        this.chooseAttrText = chooseAttrText;
        goods.thumb = [];
        const gallery = goods.gallery.split(",");
        for (const index in gallery) {
          goods.thumb.push({ imgUrl: utils.fileMgrUrl + gallery[index] });
        }

        let host = utils.host;
        goods.detail = goods.detail.replace(/..\/boss-api\//g, host);
        goods.imgUrl = utils.fileMgrUrl + goods.pic;
        goods.price = this.formatPrice(goods.price);
        this.goods = goods;
      });
    },
    formatPrice(price) {
      return utils.formatPrice(price);
    },
    changeGoodsNum(event) {
      if (event.mp.detail > this.goods.stock) {
        this.selectedNum = this.goods.stock;
        return;
      }
      this.selectedNum = event.mp.detail;

    },
    toHome() {
      const url = "/pages/index/index";
      wx.switchTab({ url });
    },
    like() {
      if (this.ifLike === false) {
        let url = '/user/favorite/add/' + this.goods.id
        this.$API.post(url).then(res => {

          if (res.success) {
            wx.showToast({ title: "收藏成功", icon: "none" });
            this.ifLike = true
          }

        });

      } else {
        let url = '/user/favorite/dislike/' + this.goods.id
        this.$API.post(url).then(res => {

          if (res.success) {
            wx.showToast({ title: "取消收藏成功", icon: "none" });
            this.ifLike = false
          }

        });

      }

    },
    goToCart() {
      wx.switchTab({ url: "/pages/cart/index" });
    },
    openAddDialog() {
      this.showDialog = true;
    },
    prepareSkuData() {
      let selAttrKeyLen = 0;
      for (let key in this.skuData.selAttrKey) {
        selAttrKeyLen++;
      }
      if (selAttrKeyLen !== this.sku.tree.length && !this.sku.none_sku) {
        wx.showToast({ title: "请先选择商品规格", icon: "none" });
        return false;
      }
      if (!this.sku.none_sku) {
        // 根据规格类别id和规格值id获取sku id
        for (let i = 0; i < this.sku.list.length; i++) {
          let notSelSku = true;
          for (let key in this.skuData.selAttrKey) {
            if (this.sku.list[i][key] !== this.skuData.selAttrKey[key]) {
              notSelSku = false;
              break;
            }
          }
          if (notSelSku) {
            this.skuData.idGoods = this.goods.id;
            this.skuData.idSku = this.sku.list[i]["id"];
            this.skuData.price = this.sku.list[i]["price"];
            break;
          }
        }
      }
      return true;
    },
    addCart() {
      // if (!this.prepareSkuData()) {
      //   return;
      // }
      // let skuData = this.skuData;


      this.$API
        .post("user/cart/add", {
          idGoods: this.goods.id,
          // idSku: this.sku.none_sku ? "" : skuData.idSku,
          count: this.selectedNum
        })
        .then(res => {
          wx.showToast({ title: "已经加入到购物车", icon: "success" });
          this.showDialog = false;
        });
    },
    closeDialog(e) {
      this.showDialog = false;
    },
    buy() {
      // this.prepareSkuData();
      // let skuData = this.skuData;
      this.$API
        .post("user/cart/add", {
          idGoods: this.goods.id,
          // idSku: this.sku.none_sku ? "" : skuData.idSku,
          count: this.selectedNum
        })
        .then(res => {
          wx.switchTab({ url: "/pages/cart/index" });
        });
    },

    chooseAttr(treeV, treeNode) {
      this.plainTest = !this.plainTest;
      let sku = this.sku;
      this.skuData.selAttrKey[treeNode.k_s] = treeV.id;
      for (let i = 0; i < sku.tree.length; i++) {
        if (sku.tree[i]["k_s"] === treeNode["k_s"]) {
          let skuSel = this.skuSel[treeNode["k_s"]];
          if (!skuSel) {
            this.skuSel[treeNode["k_s"]] = {};
          }
          // 第一个for循环将之前选中的取消掉
          for (let j = 0; j < sku.tree[i].v.length; j++) {
            if (skuSel) {
              let skuSelIdKeyIndex = skuSel["idKeyIndex"];
              let skuSelIdValIndex = skuSel["idValIndex"];
              if (skuSelIdKeyIndex > -1 && skuSelIdValIndex > -1) {
                if (skuSelIdKeyIndex === i && skuSelIdValIndex === j) {
                  sku.tree[skuSelIdKeyIndex].v[skuSelIdValIndex].plain = !sku
                    .tree[skuSelIdKeyIndex].v[skuSelIdValIndex].plain;
                }
              }
            }
          }
          // 第二个循环获取当前选中的标签标记选中
          for (let j = 0; j < sku.tree[i].v.length; j++) {
            if (sku.tree[i].v[j].id === treeV.id) {
              this.chooseAttrText[sku.tree[i]["k_s"]] = sku.tree[i].v[j].name;
              sku.tree[i].v[j].plain = !sku.tree[i].v[j].plain;
              this.skuSel[treeNode["k_s"]]["idKeyIndex"] = i;
              this.skuSel[treeNode["k_s"]]["idValIndex"] = j;
            }
          }
        }
      }
      // 必须使用以下方式更新数组，使用数组的方法或者=赋值不会触发视图更新
      this.sku.tree = [...sku.tree];
    }
  },
  onShareAppMessage() {
    return {
      title: this.goods.name,
      page: 'pages/goods/index?id=' + this.goods.id
    }
  },
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: "商品详情"
    })
    let id = options.id;
    this.goods = { thumb: [] }

    this.skuSel = {};
    this.sku = {};
    this.showDialog = false;
    this.skuData.selAttrKey = [];
    this.getGoods(id);

    if (store.state.token == null || store.state.token == undefined) {
    } else {
      // TODO
      let url = '/user/track/add/' + id
      this.$API.post(url).then(res => {

      });
    }

    let isLikeUrl = '/user/favorite/ifLike/' + id
    this.$API.get(isLikeUrl).then(res => {

      if (res.data) {
        this.ifLike = true
      } else {
        this.ifLike = false
      }
    })
    // GET {idGoods}
  }
};
</script>

<style lang="wxss">
.img {
  display: flex;
}

.swiper image {
  width: 100%;
  height: 400px;
}

.goods {
  padding: 10px;
}

.goods-desc {
  padding-left: 10px;
  font-size: 12px;
  color: #999999;
  letter-spacing: 0;
  line-height: 18px;
  margin: 6px 0;
}

.goods-detail {
  width: 100%;
  font-size: 14px;
}

.goods-title {
  padding-top: 10px;
  padding-left: 10px;
  font-size: 16px;
}

.goods-price {
  padding-left: 10px;
  padding-bottom: 10px;
  color: #f44;
}

.goods-express {
  padding-left: 10px;
  padding-bottom: 10px;
  color: #999;
  font-size: 12px;
}

.buy-count {
  margin-top: 15px;
}
.buy-action{
  padding-bottom: 8px;
}
</style>

